﻿<html>
<head>
    <meta charset="utf-8">
    <title>WebScoket调用IC卡信息(by.zytang)</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <script type="text/javascript" src="../jquery.min.js"></script>
    <script type="text/javascript" src="./jquery.min.js"></script>
</head>
<body>
<div style="padding-left:15%;padding-top:3%">
    <span style="color:red;margin-left:20px;font-size: x-large">状态：<b><i id="StatueLb"></i></b></span>
    <br/>
    <br/>
    WebScoket地址：
    <input type="text" value="127.0.0.1:61232" style="width:300px" id="WsIp" placeholder="填写已插卡并安装电子口岸网页控件的电脑IP地址">
    <input type="button" value="连接" id="ConnectBtn" style="margin-left:20px;width:80px" onclick="clickConnect()">
    <br><br>
    &nbsp;IC卡/Ukey 密码：
    <input type="password" value="" style="width:100px" id="PwTxt" maxlength="8">
    <br><br>
    <div style="border:1px;font-weight:bold;">
        发送请求：<b><i id="SendLb"></i></b><br>
        <span style="float:left">
                <textarea rows="9" cols="50" id="SignDataTxt"></textarea>
            </span>
        <br>
        <input type="button" value="获取证书编号" onclick="getCertNo()" id="btn_request1"
               style="float:left;margin-left:20px;">
        <br><br><br>
        <input type="button" value="获取公钥证书" onclick="getSignCert()" id="btn_request2"
               style="float:left;margin-left:20px;">
        <br><br><br>
        <input type="button" value="获取加签数据" onclick="getSignData()" id="btn_request3"
               style="float:left;margin-left:20px;">
        <br><br>
    </div>
    <br><br>
    <div style="border:1px;margin-top:10px;font-weight:bold;">
        接收响应：<b><i id="ReceiveLb"></i></b><br>
        <input id="respOrderCode" type="text"><br>
        <input id="respOrderId" type="text"><br>
        <textarea rows="12" cols="65" id="ReTxt"></textarea>
        <!--<br>
        <textarea rows="8" cols="65" id="ResponeTxt"></textarea>-->
    </div>
</div>

<script>
    var poolBeSign = [];
    window.onload = function () {
        var x = document.getElementById("StatueLb");
        x.innerHTML = "未连接";
    };
    window.onerror = function (msg, url, lineNo, columnNo, error) {
        // 处理error信息
        alert(msg);
    }

    var socket = null;

    function clickConnect() {
        var wsIp = document.getElementById("WsIp").value;
        if (wsIp == null || wsIp == "") {
            alert('请输入已插卡并安装电子口岸网页控件的电脑IP地址！');
            return;
        }

        var x = document.getElementById("StatueLb");
        if (socket != null) {
            if (socket.readyState == 1) {
                socket.close();
                socket = null;
                return;
            }
            ;
        }
        ;

        if (socket != null) {
            if (socket.readyState != 1) {
                socket = null;
            }
            ;
        }
        ;

        var wsImpl = window.WebSocket || window.MozWebSocket;
        x.innerHTML = "连接中...";
        window.ws = new wsImpl('ws://' + wsIp);
        ws.onmessage = function (evt) {
            //console.log(evt.data);
            //document.getElementById("ResponeTxt").value = evt.data;
            document.getElementById("SendLb").innerHTML = '';
            document.getElementById("ReceiveLb").innerHTML = '已接收响应数据';
            console.log(evt.data);
            var jsonObj = JSON.parse(evt.data);
            if (jsonObj._args["Data"] != undefined) {
                if (jsonObj._args.Data.length > 0) {
                    if (jsonObj._args.Data[0]['infos'] != undefined) {
                        document.getElementById("ReTxt").value = jsonObj._args.Data[0].infos[0];
                    } else {
                        document.getElementById("ReTxt").value = jsonObj._args.Data[0];
                        console.log(jsonObj._args.Data[0]);
                        console.log(jsonObj._method);
                        var id = $("#respOrderId").val();
                        if (jsonObj._method == "cus-sec_SpcSignDataAsPEM") {
                            pushSignedData(id, jsonObj._args.Data[0]);
                        } else {
                            pushErrorData(id,jsonObj._args.Data[0]);
                        }
                    }
                    ;
                } else if (jsonObj._args.Error.length > 0) {
                    document.getElementById("ReTxt").value = jsonObj._args.Error[0];
                }
                ;
            }
            ;
        };
        ws.onopen = function () {
            x.innerHTML = "已连接";
        };
        ws.onclose = function () {
            x.innerHTML = "已断开";
            document.getElementById("ConnectBtn").value = '连接';
            document.getElementById("SignDataTxt").value = '';
            document.getElementById("ReTxt").value = '';
            //document.getElementById("ResponeTxt").value = '';
            document.getElementById("SendLb").innerHTML = '';
            document.getElementById('ReceiveLb').innerHTML = '';
        };
        ws.onerror = function (evt) {
            alert('连接失败！');
        };
        socket = window.ws;
        document.getElementById("ConnectBtn").value = '断开';
    };

    function getCertNo() {
        if (isOpen() == true) {
            var msg = '{"_method":"cus-sec_SpcGetCertNo","_id":0,"args":{"userpin":""}}'
            //console.log('send: ' + msg);
            socket.send(msg);
            document.getElementById("SendLb").innerHTML = '发送请求中...';
            document.getElementById("ReceiveLb").innerHTML = '';
            document.getElementById("SignDataTxt").value = '';
            document.getElementById("ReTxt").value = '';
        }
        ;
    };

    function getSignCert() {
        if (isOpen() == true) {
            var msg = '{"_method":"cus-sec_SpcGetSignCertAsPEM","_id":0,"args":{"userpin":""}}'
            //console.log('send: ' + msg);
            socket.send(msg);
            document.getElementById("SendLb").innerHTML = '发送请求中...';
            document.getElementById("ReceiveLb").innerHTML = '';
            document.getElementById("SignDataTxt").value = '';
            document.getElementById("ReTxt").value = '';
        }
        ;
    };

    function getSignData() {
        if (isOpen() == true) {
            var PW = document.getElementById("PwTxt").value;
            var dataStr = document.getElementById("SignDataTxt").value;
            if (PW == null || PW == "") {
                alert('请输入IC卡/Ukey密码！');
                return;
            }
            if (dataStr == null || dataStr == "") {
                alert('请输入待加签数据！');
                return;
            }
            // var msg = '{"_method":"cus-sec_SpcSignDataAsPEM","_id":0,"args":{"passwd":"' + PW + '", "inData":"' + dataStr + '"}}'
            var reg = new RegExp('"', "g")
            var newStr = dataStr.replace(reg, '\\\"');

            var msg = "{\"_method\":\"cus-sec_SpcSignDataAsPEM\",\"_id\":0,\"args\":{\"passwd\":\"" + PW + "\",\"inData\":\"" + newStr + "\"}}"
            console.log('send: ' + msg);
            socket.send(msg);
            document.getElementById("SendLb").innerHTML = '发送请求中...';
            document.getElementById("ReceiveLb").innerHTML = '';
            //document.getElementById("SignDataTxt").value = '';
            document.getElementById("ReTxt").value = '';
        }
        ;
    };

    function isOpen() {
        if (socket != null) {
            if (socket.readyState == 1)
                return true;
        }
        ;

        console.log('请先打开Websocket连接！');
        return false;
    };


    function pullData() {
        $("#PwTxt").val(88888888);
        if (isOpen() == true) {

            var url = "http://localhost:8821/loop/get";
            $.get(url, function (result) {
                console.log(result);
                var length = result.length;
                if (length > 0) {
                    for (var i = 0; i < length; i++) {
                        poolBeSign.push(result[i]);
                    }
                }
            });
        } else {
            $("#ConnectBtn").click();
            if (isOpen() == true) {
                var url = "http://localhost:8821/loop/get";
                $.get(url, function (result) {
                    console.log(result);
                });
            }
        }
    }

    function pullToSign() {
        var len = poolBeSign.length;
        console.log(poolBeSign);

        for (var i = 0; i < len; i++) {
            var element = poolBeSign[i];
            console.log(element);
            $("#SignDataTxt").text(element.fromData);
            $("#respOrderId").val(element.id);
            $("#respOrderCode").val(element.orderCode);
            getSignData();
            poolBeSign.shift();
        }
    }

    function pushSignedData(id, signedData) {
        console.log(id);
        console.log(signedData);
        $.ajax({
            type: "POST",
            url: "http://localhost:8821/loop/push/one",
            data: {
                "id": id,
                "signedData": signedData,
            },
            // processData: false,
            contentType: "application/x-www-form-urlencoded",
            success: function (data) {
                console.log("推送成功");
            }

        })
    }

    function pushErrorData(id, reason) {
        console.log(id);
        console.log(reason);
        $.ajax({
            type: "POST",
            url: "http://localhost:8821/loop/push/Error",
            data: {
                "id": id,
                "reason": reason,
            },
            // processData: false,
            contentType: "application/x-www-form-urlencoded",
            success: function (data) {
                console.log("推送异常,成功");
            }

        })
    }

    $(function () {
        setInterval(pullData, 2000);
        setInterval(pullToSign, 1000);
    });
</script>
</body>
</html>
